<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>Spring Boot之文件上传与下载 | 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~ | It&#39;s founded on March 9, 2019 and the open source address for the blog notes https://github.com/YUbuntu0109/YUbuntu0109.github.io</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="Spring Boot">
    <meta name="description" content="学习笔记 : Spring Boot之文件上传关键字 : Servlet 3.0 、 SpringMVC 、 Spring Boot 简介前天使用Sprint Boot开发了一个基于SSM框架的项目,一个简单的好友备忘录,该项目地址 : https://github.com/YUbuntu0109/SpringBoot-CURD-Memo ,在该项目中除了基本的CURD,还添加了上传用户头像的功能">
<meta name="keywords" content="Spring Boot">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot之文件上传与下载">
<meta property="og:url" content="https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/index.html">
<meta property="og:site_name" content="欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~">
<meta property="og:description" content="学习笔记 : Spring Boot之文件上传关键字 : Servlet 3.0 、 SpringMVC 、 Spring Boot 简介前天使用Sprint Boot开发了一个基于SSM框架的项目,一个简单的好友备忘录,该项目地址 : https://github.com/YUbuntu0109/SpringBoot-CURD-Memo ,在该项目中除了基本的CURD,还添加了上传用户头像的功能">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2019-12-12T15:00:32.227Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring Boot之文件上传与下载">
<meta name="twitter:description" content="学习笔记 : Spring Boot之文件上传关键字 : Servlet 3.0 、 SpringMVC 、 Spring Boot 简介前天使用Sprint Boot开发了一个基于SSM框架的项目,一个简单的好友备忘录,该项目地址 : https://github.com/YUbuntu0109/SpringBoot-CURD-Memo ,在该项目中除了基本的CURD,还添加了上传用户头像的功能">
    
        <link rel="alternate" type="application/atom+xml" title="欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/my-portrait.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">黄宇辉</h5>
          <a href="mailto:3083968068@qq.com" title="3083968068@qq.com" class="mail">3083968068@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                Homepage
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/YUbuntu0109" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://space.bilibili.com/364361791" target="_blank" >
                <i class="icon icon-lg icon-link"></i>
                Bilibili
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">Spring Boot之文件上传与下载</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="Search">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        

        <!-- background music(Mar 11,2019 AM) -->
        <div>
            <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=280 height=52 src="//music.163.com/outchain/player?type=2&id=438801642&auto=1&height=32"></iframe>
        </div>
        <!---------------------->
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">Spring Boot之文件上传与下载</h1>
        <h5 class="subtitle">
            
                <time datetime="2019-06-30T21:22:23.000Z" itemprop="datePublished" class="page-time">
  2019-06-30
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#学习笔记-Spring-Boot之文件上传"><span class="post-toc-number">1.</span> <span class="post-toc-text">学习笔记 : Spring Boot之文件上传</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#简介"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">简介</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#异常分析"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">异常分析</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#问题分析"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">问题分析</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#解决方案"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">解决方案</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#使用绝对路径"><span class="post-toc-number">1.4.1.</span> <span class="post-toc-text">使用绝对路径</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#修改location的值"><span class="post-toc-number">1.4.2.</span> <span class="post-toc-text">修改location的值</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#示例程序"><span class="post-toc-number">1.5.</span> <span class="post-toc-text">示例程序</span></a></li></ol></li></ol>
        </nav>
    </aside>


<article id="post-Spring-Boot之文件上传"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">Spring Boot之文件上传与下载</h1>
        <div class="post-meta">
            <time class="post-time" title="2019-06-30 21:22:23" datetime="2019-06-30T21:22:23.000Z"  itemprop="datePublished">2019-06-30</time>

            


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h2 id="学习笔记-Spring-Boot之文件上传"><a href="#学习笔记-Spring-Boot之文件上传" class="headerlink" title="学习笔记 : Spring Boot之文件上传"></a>学习笔记 : Spring Boot之文件上传</h2><p><em>关键字 : <code>Servlet 3.0</code> 、 <code>SpringMVC</code> 、 <code>Spring Boot</code></em></p>
<h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p><em>前天使用Sprint Boot开发了一个基于SSM框架的项目,一个简单的好友备忘录,该项目地址 : <a href="https://github.com/YUbuntu0109/SpringBoot-CURD-Memo" target="_blank" rel="noopener">https://github.com/YUbuntu0109/SpringBoot-CURD-Memo</a> ,在该项目中除了基本的CURD,还添加了上传用户头像的功能哟~ 以至于在写此功能时发现了Spring Boot在上传文件时不同于<code>Spring MVC</code>的一个细节问题 : <code>头像被上传到非预期路径下!</code></em></p>
<ul>
<li><em>注 : Spring Boot启动时会创建一个<code>/tmp/tomcat.xxxxxx/work/Tomcat/localhost/ROOT</code>的临时目录作为文件上传的临时目录,但是该目录会在<code>10</code>天之后被系统自动清理掉 !`</em></li>
</ul>
<p><em>继而程序抛出如下异常信息 :</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">java.io.IOException: java.io.FileNotFoundException:</span><br><span class="line">/tmp/tomcat.273391201583741210.8080/work/Tomcat/localhost/ROOT/upload/portrait/myportrait.jpg (No such file or directory)...</span><br></pre></td></tr></table></figure></p>
<h3 id="异常分析"><a href="#异常分析" class="headerlink" title="异常分析"></a>异常分析</h3><p><em><code>upload/portrait</code>是我用于存储头像的项目目录,而<code>transferTo(File dest)</code>方法预期写入的文件路径为<code>/tmp/tomcat.273391201583741210.8080/work/Tomcat/localhost/ROOT/upload/portrait/</code>,我们并没有创建该目录,因此会抛出此异常信息 !</em></p>
<h3 id="问题分析"><a href="#问题分析" class="headerlink" title="问题分析"></a>问题分析</h3><p><em>为什么会这样呢 ? 相对路径-预期路径应该是项目路径<code>/tmp/source/</code>,但是报错确是一个系统临时文件路径,由于是写入文件时报错,继而我们来查看一下<code>transferTo(File dest)</code>的源码吧 :</em></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> org.apache.catalina.core;</span><br><span class="line"><span class="comment">//......</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Adaptor to allow &#123;<span class="doctag">@link</span> FileItem&#125; objects generated by the package renamed</span></span><br><span class="line"><span class="comment"> * commons-upload to be used by the Servlet 3.0 upload API that expects</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> Part&#125;s.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ApplicationPart</span> <span class="keyword">implements</span> <span class="title">Part</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//......</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">write</span><span class="params">(String fileName)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        File file = <span class="keyword">new</span> File(fileName);</span><br><span class="line">        <span class="keyword">if</span> (!file.isAbsolute()) &#123;</span><br><span class="line">            file = <span class="keyword">new</span> File(location, fileName);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            fileItem.write(file);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IOException(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><em>由源码可知,在使用<code>Servlet3.0</code>支持的上传文件功能时,若我们没有使用绝对路径,<code>transferTo(File dest)</code>方法会在相对路径前添加一个<code>location</code>路径 ! 继而影响了SpringMVC的<code>MultipartFile</code>的使用 .</em></p>
<h3 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h3><h4 id="使用绝对路径"><a href="#使用绝对路径" class="headerlink" title="使用绝对路径"></a>使用绝对路径</h4><p><em>通过<code>ResourceUtils.getURL(&quot;classpath:&quot;).getPath()</code>获取项目的绝对路径,为防止项目路径中含有空格等特殊字符继而乱码,可以通过<code>URLDecoder.decode(String s, Charset charset)</code>对其进行解码.</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//项目下存储头像的目录</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> String uploadPath = <span class="string">"/static/upload/friend_portrait/"</span>;</span><br><span class="line"><span class="comment">//指定存储头像目录的完整路径(项目发布路径):若不使用绝对路径,则Spring boot会默认将上传的文件存储到临时目录中</span></span><br><span class="line">String dirPath = URLDecoder.decode(ResourceUtils.getURL(<span class="string">"classpath:"</span>).getPath(), StandardCharsets.UTF_8) + uploadPath;</span><br></pre></td></tr></table></figure></p>
<p><em>注 : 当我们使用<code>ClassLoader()</code>的<code>getResource()</code>方法获取路径时,获取到的路径是已被<code>URLEncoder.encode(path,&quot;utf-8&quot;)</code>编码了的,当路径中存在中文和空格时,它会对这些字符进行转换,继而得到的往往不是我们想要的真实路径,所以我们可以调用<code>URLDecoder.decode(String s, Charset charset)</code>方法进行解码,以便得到原始的中文及空格路径. 发送的时候使用<code>encode(String s, Charset charset)</code>编码,接收的时候使用<code>URLDecoder.decode(String s, Charset charset)</code>解码,按指定的编码格式进行编码、解码,可以保证不会出现乱码哟 ~</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式</span></span><br><span class="line">URLEncoder.encode(String s, Charset charset)</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用指定的编码机制对 application/x-www-form-urlencoded 字符串解码</span></span><br><span class="line">URLDecoder.decode(String s, Charset charset)</span><br></pre></td></tr></table></figure></p>
<h4 id="修改location的值"><a href="#修改location的值" class="headerlink" title="修改location的值"></a>修改location的值</h4><p><em><code>location</code>可以理解为临时文件目录,可以通过配置<code>location</code>的值,使其指向我们的项目路径,继而来解决此问题. 只需在Spring Boot启动类中添如下代码 :</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"> <span class="meta">@Bean</span></span><br><span class="line"> <span class="function">MultipartConfigElement <span class="title">multipartConfigElement</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    MultipartConfigFactory factory = <span class="keyword">new</span> MultipartConfigFactory();</span><br><span class="line">    factory.setLocation(<span class="string">"/app/pttms/tmp"</span>);</span><br><span class="line">    <span class="keyword">return</span> factory.createMultipartConfig();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="示例程序"><a href="#示例程序" class="headerlink" title="示例程序"></a>示例程序</h3><p><em>该上传文件的示例程序摘自我的Sping Boot-好友备忘录小项目,程序中使用<code>绝对路径</code>方案来解决上述问题,该程序具有参考与学习价值哟~</em></p>
<ol>
<li><p><em>FriendController.java : 好友信息控制器</em></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> pers.haungyuhui.memo.controller;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.github.pagehelper.PageHelper;</span><br><span class="line"><span class="keyword">import</span> com.github.pagehelper.PageInfo;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Controller;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.ResourceUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.*;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.multipart.MultipartFile;</span><br><span class="line"><span class="keyword">import</span> pers.haungyuhui.memo.bean.Friend;</span><br><span class="line"><span class="keyword">import</span> pers.haungyuhui.memo.service.FriendService;</span><br><span class="line"><span class="keyword">import</span> pers.haungyuhui.memo.util.UploadFile;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> java.io.FileNotFoundException;</span><br><span class="line"><span class="keyword">import</span> java.net.URLDecoder;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@project</span>: memo</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 控制器-管理好友信息页面</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: 黄宇辉</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 6/28/2019-8:25 PM</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span>: 1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@website</span>: https://yubuntu0109.github.io/</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/memo"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StudentController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//......</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//项目下存储头像的目录,需放在静态资源'static'目录下哟</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String uploadPath = <span class="string">"/static/upload/friend_portrait/"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@description</span>: 上传头像-原理:将头像上传到项目发布目录中,通过读取数据库中的头像路径来显示头像</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: photo</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: request</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@date</span>: 2019-06-29 4:20 PM</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span>: java.util.Map&lt;java.lang.String, java.lang.Object&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@PostMapping</span>(<span class="string">"/uploadPhoto"</span>)</span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String, Object&gt; <span class="title">uploadPhoto</span><span class="params">(MultipartFile photo)</span> <span class="keyword">throws</span> FileNotFoundException </span>&#123;</span><br><span class="line">        <span class="comment">//指定存储头像目录的完整路径(项目发布路径): 若不使用绝对路径,则Spring boot会默认将上传的文件存储到临时目录中</span></span><br><span class="line">        String dirPath = URLDecoder.decode(ResourceUtils.getURL(<span class="string">"classpath:"</span>).getPath(), StandardCharsets.UTF_8) + uploadPath;</span><br><span class="line">        <span class="comment">//返回头像的上传结果</span></span><br><span class="line">        <span class="keyword">return</span> UploadFile.getUploadResult(photo, dirPath, uploadPath);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><em>UploadFile.java : 上传文件的工具类</em></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> pers.haungyuhui.memo.util;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.apache.commons.io.filefilter.SuffixFileFilter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.multipart.MultipartFile;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.File;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.UUID;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@project</span>: memo</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 上传文件工具类</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: 黄宇辉</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 6/29/2019-9:38 AM</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span>: 1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@website</span>: https://yubuntu0109.github.io/</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UploadFile</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//限制头像大小最大为20M</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> MAX_SIZE = <span class="number">20971520</span>;</span><br><span class="line">    <span class="comment">//存储文件上传失败的错误信息</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String, Object&gt; error_result = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="comment">//存储头像的上传结果信息</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String, Object&gt; upload_result = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="comment">//指定上传文件的类型</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] suffixs = <span class="keyword">new</span> String[]&#123;<span class="string">".png"</span>, <span class="string">".PNG"</span>, <span class="string">".jpg"</span>, <span class="string">".JPG"</span>, <span class="string">".jpeg"</span>, <span class="string">".JPEG"</span>, <span class="string">".gif"</span>, <span class="string">".GIF"</span>, <span class="string">".bmp"</span>, <span class="string">".BMP"</span>&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@description</span>: 效验所上传图片的大小及格式等信息...</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: photo</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: path</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@date</span>: 2019-06-29 9:40 AM</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span>: java.util.Map&lt;java.lang.String, java.lang.Object&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String, Object&gt; <span class="title">uploadPhoto</span><span class="params">(MultipartFile photo, String path)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//若存储文件的目录路径不存在,则创建该目录</span></span><br><span class="line">        File filePath = <span class="keyword">new</span> File(path);</span><br><span class="line">        <span class="keyword">if</span> (!filePath.exists()) &#123;</span><br><span class="line">            filePath.mkdirs();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//限制上传文件的大小</span></span><br><span class="line">        <span class="keyword">if</span> (photo.getSize() &gt; MAX_SIZE) &#123;</span><br><span class="line">            error_result.put(<span class="string">"success"</span>, <span class="keyword">false</span>);</span><br><span class="line">            error_result.put(<span class="string">"msg"</span>, <span class="string">"上传的图片大小不能超过20M哟!"</span>);</span><br><span class="line">            <span class="keyword">return</span> error_result;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 限制上传的文件类型</span></span><br><span class="line">        SuffixFileFilter suffixFileFilter = <span class="keyword">new</span> SuffixFileFilter(suffixs);</span><br><span class="line">        <span class="keyword">if</span> (!suffixFileFilter.accept(<span class="keyword">new</span> File(path + photo.getOriginalFilename()))) &#123;</span><br><span class="line">            error_result.put(<span class="string">"success"</span>, <span class="keyword">false</span>);</span><br><span class="line">            error_result.put(<span class="string">"msg"</span>, <span class="string">"禁止上传此类型文件! 请上传图片哟!"</span>);</span><br><span class="line">            <span class="keyword">return</span> error_result;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@description</span>: 获取头像的上传结果信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: photo</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: dirPaht</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span>: portraitPath</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@date</span>: 2019-06-29 9:44 AM</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span>: java.util.Map&lt;java.lang.String, java.lang.Object&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Map&lt;String, Object&gt; <span class="title">getUploadResult</span><span class="params">(MultipartFile photo, String dirPath, String uploadPath)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!photo.isEmpty() &amp;&amp; photo.getSize() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">//效验图片-error_result: 存储头像上传失败的错误信息</span></span><br><span class="line">            Map&lt;String, Object&gt; error_result = uploadPhoto(photo, dirPath);</span><br><span class="line">            <span class="keyword">if</span> (error_result != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> error_result;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//使用UUID重命名图片名称(uuid__原始图片名称)</span></span><br><span class="line">            String newPhotoName = UUID.randomUUID() + <span class="string">"__"</span> + photo.getOriginalFilename();</span><br><span class="line">            <span class="comment">//将上传的图片保存到目标目录下</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                photo.transferTo(<span class="keyword">new</span> File(dirPath + newPhotoName));</span><br><span class="line">                <span class="comment">//将存储头像的目录路径返回给页面</span></span><br><span class="line">                upload_result.put(<span class="string">"success"</span>, <span class="keyword">true</span>);</span><br><span class="line">                upload_result.put(<span class="string">"portrait_path"</span>, uploadPath + newPhotoName);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">                upload_result.put(<span class="string">"success"</span>, <span class="keyword">false</span>);</span><br><span class="line">                upload_result.put(<span class="string">"msg"</span>, <span class="string">"上传文件失败! 服务器端发生异常!"</span>);</span><br><span class="line">                <span class="keyword">return</span> upload_result;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            upload_result.put(<span class="string">"success"</span>, <span class="keyword">false</span>);</span><br><span class="line">            upload_result.put(<span class="string">"msg"</span>, <span class="string">"头像上传失败! 未找到指定图片!"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> upload_result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    Last updated: <time datetime="2019-12-12T15:00:32.227Z" itemprop="dateUpdated">2019-12-12 15:00:32</time>
</span><br>


        
    </div>
    
    <footer>
        <a href="https://yubuntu0109.github.io">
            <img src="/img/my-portrait.jpg" alt="黄宇辉">
            黄宇辉
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Spring-Boot/">Spring Boot</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/&title=《Spring Boot之文件上传与下载》 — 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~&pic=https://yubuntu0109.github.io/img/my-portrait.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/&title=《Spring Boot之文件上传与下载》 — 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~&source=My Personal Website For Blog" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Spring Boot之文件上传与下载》 — 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~&url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/&via=https://yubuntu0109.github.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2019/07/01/Spring-Boot拥抱MyBatis及Redis/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Spring-Boot拥抱MyBatis及Redis ~</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2019/06/30/Spring-Boot项目-好友备忘录/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Spring Boot项目:好友备忘录</h4>
      </a>
    </div>
  
</nav>



    




















</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        thanks ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/img/Wechat_appreciates.png" alt="打赏二维码">
        </div>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        

        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>This blog is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>.</span>
        </p>
    </div>
    <div class="bottom">
        <!-- 统计网站用户访问量. 技术支持：不蒜子(http://busuanzi.ibruce.info/) ————> Mar 13,2019 -->
        <p>
            <font style='font-size: 12px;color:springgreen'>
                    <div align="center">
                        <!-- 安装脚本 -->
                        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
                        <!-- 安装标签 -->
                        <span id="busuanzi_container_site_pv">
                            ◎用户总访问量 : <span id="busuanzi_value_site_pv"></span> 次 ~ &nbsp&nbsp
                        </span>
                        <span id="busuanzi_container_site_uv">
                            ◎总访客数(（づ￣3￣）づ╭❤～) : <span id="busuanzi_value_site_uv"></span>人 ~
                        </span>
                    </div>
                </font>
            </p>
            <!---------->
            <p>
                <font style='font-size: 10px'>
                    <span>黄宇辉 &copy; 2019</span>
                    <span>
                        
                        Blog source <a href="https://github.com/YUbuntu0109/YUbuntu0109.github.io" target="_blank">Github</a> 
                        Power by <a href="http://hexo.io/" target="_blank">Hexo</a>
                        Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
                    </span>
                </font>
            </p>
        </div>
    </footer>
    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/&title=《Spring Boot之文件上传与下载》 — 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~&pic=https://yubuntu0109.github.io/img/my-portrait.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/&title=《Spring Boot之文件上传与下载》 — 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~&source=My Personal Website For Blog" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Spring Boot之文件上传与下载》 — 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~&url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/&via=https://yubuntu0109.github.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=https://yubuntu0109.github.io/2019/06/30/Spring-Boot之文件上传/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>








<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = 'Where are you going ?';
            clearTimeout(titleTime);
        } else {
            document.title = 'As long as you love me ~';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
